//
//  FirstNavigationView.m
//  L7_test
//
//  Created by Mac on 11-12-29.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "FirstNavigationView.h"
#import "ShopListController.h"
#import "DetailShopViewController.h"
#import "ResolveXML.h"
#import "GDataXMLNode.h"
#import "AppDelegate.h"
#import "SupplierManager.h"
#import "PublicFunction.h"
#import "FMDBManager.h"
#import "FMDatabase.h"
#import "NetWorkManager.h"
#import "FMDBCollectionManager.h"
#import "FMDBTransactionHistory.h"
#import "TransactionHistory.h"
#import "UICustomImageView.h"
#import "SearchController.h"
#import "SearchShopListController.h"
#define ISNULL @"1"   //1为空
@implementation FirstNavigationView


//加载本地nib文件
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

//修改搜索栏取消按钮内容和样式
- (void)searchBarTextDidBeginEditing:(UISearchBar *)hsearchBar
{
    hsearchBar.showsCancelButton = YES;
    for(id cc in [hsearchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setBackgroundColor:[UIColor clearColor]];
            [btn setBackgroundImage:[UIImage imageNamed:@"003.png"] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageNamed:@"003.png"] forState:UIControlStateHighlighted];
            [btn setTitleShadowColor:[UIColor grayColor] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(cancelInput:) forControlEvents:UIControlEventTouchUpInside];
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { 
    NSLog(@"进入");
    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    NSArray *suppliers;
    if([appDelegate status]){
//        //联网状态
//        suppliers=nil;

        //离线状态
        suppliers=[fmdbSupplierManager getSuppliersByNameOrDishAndPage:[searchBar text] sPage:@"1"];
        for(Supplier *supplier in suppliers){
            NSLog(@"快速的遍历数组对象为: %@ %@",supplier.supplierName,supplier.address);
        }
    }
    else{
        //离线状态
        suppliers=[fmdbSupplierManager getSuppliersByNameOrDishAndPage:[searchBar text] sPage:@"1"];
        for(Supplier *supplier in suppliers){
            NSLog(@"快速的遍历数组对象为: %@ %@",supplier.supplierName,supplier.address);
        }
    }
    if (suppliers == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        return;
    }
    //创建新的试图并将试图推入栈中
    SearchShopListController *shopListController = [[SearchShopListController alloc]initWithNibName:@"SearchShopListController" bundle:nil];
    UINavigationController  *theNavController = [[UINavigationController alloc]
                                                 initWithRootViewController:shopListController];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:2];
    [dictionary setObject:supplierCategories forKey:@"SupplierCategories"];
    [dictionary setObject:suppliers forKey:@"Suppliers"];
    shopListController.searchType=@"0";//进入直接搜索
    shopListController.conditions=[searchBar text];//直接搜索条件
    [shopListController setRecieveDictionary:dictionary];
    [shopListController initMembers];
    [shopListController release];
    theNavController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController pushViewController: shopListController animated:YES];
    [theNavController release];
}

- (IBAction)cancelInput:(id)sender{
    [searchBarCustom resignFirstResponder];
}

//初始化searchBar
-(void)initSearchBar{
    //search bar
    searchBarCustom = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 
    //添加文本默认内容
    searchBarCustom.placeholder=@"请输入商铺名称或菜品"; 
    //设置取消按钮
    searchBarCustom.showsCancelButton=YES;
    //改变searchbar颜色
    //移出原背景颜色
    UIView *segment=[searchBarCustom.subviews objectAtIndex:0];
    [segment removeFromSuperview];
    //设置背景为白色
    searchBarCustom.backgroundColor=[UIColor whiteColor];
    //修改取消按钮文字
    [self searchBarTextDidBeginEditing:searchBarCustom];
    //添加searchbar背景图片
    UIImageView* searchbarImg=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,44)];
    [searchbarImg setImage:[UIImage imageNamed:@"001.png"]];  
    [searchBarCustom insertSubview:searchbarImg atIndex:0];
    [searchbarImg release];
    searchBarCustom.delegate=self;

    
    
    [self.view addSubview:searchBarCustom];
}

//初始化滚动背景
-(void)initScrollView{
    //Scrollview 
    bgScrView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,44,320,327)];
    [bgScrView setBackgroundColor:[UIColor whiteColor]];
    //设置为滚动
    bgScrView.pagingEnabled = YES; 
    //设置滚动的内容大小
    [bgScrView setContentSize:CGSizeMake(320,330)];
    //添加滚动背景
    [self.view addSubview:bgScrView];
}

//生成按钮
-(void)setSuppierCategoryBtn:(UIView *)view{
    if([appDelegate status]){
        NSLog(@"联网状态");
        manager = [[SupplierCategoryManager alloc] init];
        supplierCategories = [manager getAllSupplierCategories];
        recieveDictionary = [[NSMutableDictionary alloc] init];
        [recieveDictionary setObject: supplierCategories forKey:@"SupplierCategories"];
        //添加商店类型到本地数据库
        [fmdbSupplierCategoryManager insertSupplierCategory:recieveDictionary];
    }
    else{
        NSLog(@"离线状态");
        supplierCategories=[fmdbSupplierCategoryManager getSupplierCategoryForLocal];
        recieveDictionary = [[NSMutableDictionary alloc] init];
        [recieveDictionary setObject: supplierCategories forKey:@"SupplierCategories"];
    }
    CGFloat leftX = 0;
    CGFloat rightX = 160;
    CGFloat defaultY = 160;
    for (int i = 0; i < [supplierCategories count]; i++) {
        SupplierCategory *supplierCategory =(SupplierCategory *)[supplierCategories objectAtIndex:i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        //设置按钮内容
        [button setTitle:supplierCategory.supplierCategoryName forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
        //设置按钮tag
        [button setTag:supplierCategory.supplierCategoryId];
        [button setBackgroundImage:[UIImage imageNamed:@"014.png"] forState:UIControlStateNormal];
        
        CGFloat x = i % 2==0 ? leftX : rightX;
        CGFloat y = defaultY + (i / 2) * 36;
        button.frame = CGRectMake( x, y, 162, 40);
        
        //图标
        UIImageView* goView=[[UIImageView alloc] initWithFrame:CGRectMake(x+140,y+13,10,12)];
        [goView setImage:[UIImage imageNamed:@"015.png"]];  
        [goView setUserInteractionEnabled:YES];  
        
        [button addTarget:self action:@selector(showShopBtn:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
        [view addSubview:goView];
        [goView release];
        //使用scrollview的话释放button就无法显示
        //        [button release];
    }
}

//初始化最近浏览
-(void)initTransactionHistory{
    //初始化最近浏览样式
    fmdbTransactionHistory=[[FMDBTransactionHistory alloc]init];
    transactionHistorys=[fmdbTransactionHistory getAllHistory];
    [fmdbTransactionHistory release];
    //添加最新浏览大背景
    topView=[[UIView alloc]init];
    topView.frame=CGRectMake(0, 0, 320, 150);
    [bgScrView addSubview:topView];
    //最近浏览背景图片
    UIImageView *imageView;
    int count=0;
    int indexX=0;
    int indexY=0;
    for(int i=0;i<2;i++){
        if(i==0){
            indexY=6;
        }
        else{
            indexY=81;
        }
        for(int j=0;j<4;j++){
            if(j==0){
                indexX=16;
            }
            else{
                indexX=indexX+76;
            }
            imageView=[[UIImageView alloc] initWithFrame:CGRectMake(indexX,indexY,60,69)];
            [imageView setImage:[UIImage imageNamed:@"008.png"]];  
            [imageView setUserInteractionEnabled:YES]; 
            [imageView removeFromSuperview];
            [topView addSubview:imageView];
            
            if([transactionHistorys objectAtIndex:count]==ISNULL){
                //如果没有收藏商铺
                UIImageView* addImg=[[UIImageView alloc] initWithFrame:CGRectMake(15,18,30,30)];
                [addImg setImage:[UIImage imageNamed:@"013.png"]];  
                [addImg setUserInteractionEnabled:YES];  
                [imageView addSubview:addImg];
            }
            else{
                //如果有收藏商铺
                //添加图片和名称
                //图片
                UICustomImageView *supplierImg=[[UICustomImageView alloc] initWithFrame:CGRectMake(5,4,50,50)];
                UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                imgBtn.frame=CGRectMake(5, 4, 50, 50);
                [imgBtn setTag:[[transactionHistorys objectAtIndex:count] supplierId]];
                imgBtn.backgroundColor = [UIColor clearColor];
                [imgBtn addTarget:self action:@selector(showDetailShop:) forControlEvents:UIControlEventTouchUpInside];
                
                //有商铺图片
                [supplierImg setContentMode:UIViewContentModeScaleAspectFit];
                [supplierImg setUserInteractionEnabled:YES];
                [supplierImg setImage:nil];
                [supplierImg setImageURL:[[transactionHistorys objectAtIndex:count] imgUrl]];
                
                //名称背景
                UIButton *supplierNameBg=[UIButton buttonWithType:UIButtonTypeCustom];
                supplierNameBg.frame=CGRectMake(3,50, 54, 15);
                [supplierNameBg setBackgroundImage:[UIImage imageNamed:@"010.png"] forState:UIControlStateNormal];
                [supplierNameBg setTag:[[transactionHistorys objectAtIndex:count] supplierId]];
                [supplierNameBg addTarget:self action:@selector(showDetailShop:) forControlEvents:UIControlEventTouchUpInside];
                //修改店铺长度为4
                if([[transactionHistorys objectAtIndex:count] supplierName].length>4){
                NSString *supplierNameShort = [[[transactionHistorys objectAtIndex:count] supplierName] substringToIndex:4];
                [[transactionHistorys objectAtIndex:count] setSupplierName:supplierNameShort];
                }
                [supplierNameBg setTitle:[[transactionHistorys objectAtIndex:count] supplierName] forState:UIControlStateNormal];
                supplierNameBg.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:12]; 
                [imageView addSubview:supplierImg];
                [imageView addSubview:imgBtn];
                [imageView addSubview:supplierNameBg];
                [supplierImg release];
            }
            count++;
        }
    }
}

- (void)viewDidLoad
{
    //判断网络是否连接
    NetWorkManager *netWorkManager=[[NetWorkManager alloc]init];
    //初始化代理
    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;	
    appDelegate.status=[netWorkManager netWorkStatus];
    [netWorkManager release];
    //初始化本地商铺类型管理
    fmdbSupplierCategoryManager=[[FMDBSupplierCategoryManager alloc]init];
    //初始化数据库，创建表
    FMDBManager *fmdbManager=[[FMDBManager alloc]init];
    [fmdbManager initDataBase];
    [fmdbManager release];
    //设置view为白色背景
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //初始化索搜栏
    [self initSearchBar];
    //初始化滚动背景
    [self initScrollView];
    //初始化店铺类型按钮
    [self setSuppierCategoryBtn:bgScrView];
    //初始化广告位
    UIImageView* bnView=[[UIImageView alloc] initWithFrame:CGRectMake(0,371,320,40)];
    [bnView setImage:[UIImage imageNamed:@"ban.png"]];  
    [bnView setUserInteractionEnabled:YES];  
    [self.view addSubview:bnView];
    [bnView release];
    //设置视图title
    [PublicFunction CreateImageFolder];
    self.title=@"首页";
    //设置搜索页面的值
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:1];
    [dictionary setObject:supplierCategories forKey:@"SupplierCategories"];
    [appDelegate setRecieveDictionary:dictionary];
    [super viewDidLoad];
}


- (void)viewWillAppear:(BOOL)animated{
    //隐藏导航栏
    self.navigationController.navigationBarHidden=YES;
    [self initTransactionHistory];
}

//显示商家列表信息
- (IBAction)showShopBtn:(id)sender {
    SupplierManager *supplierManager = [[SupplierManager alloc] init];
    NSString *categoryId = [NSString stringWithFormat:@"%d",[sender tag]];
    NSArray *suppliers;
    if([appDelegate status]){
        //联网状态
        suppliers = [supplierManager getSupplier:categoryId pageIndex:1 road:nil isSelling:nil];
    }
    else{
        //离线状态
        fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
        suppliers=[fmdbSupplierManager getSupplierByCategoryIdAndPageFromLoc:categoryId sPage:@"1" road:nil isSelling:nil];
        [fmdbSupplierManager release];
    }
    if (suppliers == nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"没有该类型的商家" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        [supplierManager release];
        return;
    }
    //创建新的试图并将试图推入栈中
    ShopListController *shopListController = [[ShopListController alloc]initWithNibName:@"ShopListController" bundle:nil];
    UINavigationController  *theNavController = [[UINavigationController alloc]
                                                 initWithRootViewController:shopListController];
    //传递tag值
    shopListController.supplierCategoryTag=[sender tag];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:2];
    [dictionary setObject:supplierCategories forKey:@"SupplierCategories"];
    [dictionary setObject:suppliers forKey:@"Suppliers"];
    [shopListController setRecieveDictionary:dictionary];
    [shopListController initMembers];
    [supplierManager release];
    [shopListController release];
    theNavController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController pushViewController: shopListController animated:YES];
    [theNavController release];
}

//显示商家详细信息
- (IBAction)showDetailShop:(id)sender {
    NSString *supplierId = [NSString stringWithFormat:@"%d",[sender tag]];
    Supplier *supplierDetail;
    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    supplierDetail=[fmdbSupplierManager getSupplierDetailByIdFromLoc:supplierId];
    [fmdbSupplierManager release];
    //创建新的试图并将试图推入栈中
    DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]initWithNibName:@"DetailShopViewController" bundle:nil];
    UINavigationController  *theNavController = [[UINavigationController alloc]
                                                 initWithRootViewController:detailShopViewController];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :2];
    [dictionary setObject:supplierId forKey:@"supId"];
    [dictionary setObject:supplierDetail forKey:@"Supplier"];
    [detailShopViewController setRecieveDictionary:dictionary];
    [detailShopViewController release];
    theNavController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController pushViewController: detailShopViewController animated:YES];
    [theNavController release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)viewDidDisappear:(BOOL)animated{
    [topView removeFromSuperview];
    [searchBarCustom resignFirstResponder];
}

- (void)dealloc {
    if (manager!=nil) {
        [manager release];
    }
    [topView release];
    [bgScrView release];
    [searchBarCustom release];
    [super dealloc];
}
@end
